package com.example.java_chatroom1.component;

import com.example.java_chatroom1.model.Friend;
import com.example.java_chatroom1.model.MessageInfo;
import com.example.java_chatroom1.model.User;
import com.example.java_chatroom1.model.WebSocketMessage;
import com.example.java_chatroom1.server.MessageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class WebSocketComponent extends TextWebSocketHandler {
    private Map<Integer,WebSocketSession> map = new HashMap<>();

    @Autowired
    private MessageService messageService;

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        User user = (User) session.getAttributes().get("user");
        //一个账号不可多台主机登录
        if (map.get(user.getUserId()) != null) {
            session.close();
            return;
        }
        map.put(user.getUserId(), session);
        log.info(user.getUserName() + "websocket连接成功！");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User user = (User) session.getAttributes().get("user");
        log.info(user.getUserName() + ": " + message.toString());
        WebSocketMessage webSocketMessage = objectMapper.readValue(message.getPayload(),WebSocketMessage.class);
        List<Friend> friends = messageService.getFriendBySessionId(webSocketMessage.getSessionId(), user.getUserId());
        for (Friend friend : friends) {
            Integer friendId = friend.getFriendId();
            WebSocketSession friendSession = map.get(friendId);
            if (friendSession != null) {
                friendSession.sendMessage(message);
            }
        }
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setSessionId(webSocketMessage.getSessionId());
        messageInfo.setFromId(user.getUserId());
        messageInfo.setMessage(webSocketMessage.getContent());
        messageService.addMessageInfo(messageInfo);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        User user = (User) session.getAttributes().get("user");
        log.error(user.getUserName() + ": " + exception.toString());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        User user = (User) session.getAttributes().get("user");
        log.info(user.getUserName() + "：断开连接");
        map.remove(user.getUserId());
    }
}
